package com.yupi.lxrapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.lxrapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.yupi.lxrapiclientsdk.utils.SignUtils.genSign;


/**
 * @Author: LiangXinRui
 * @Date: 2023/07/12/16:08
 * @Description: 调用第三方接口的客户端
 */
public class YuApiClient {

    private String accessKey;

    private String secretKey;

    private static final String GATEWAY_HOST = "http://localhost:8090";


    public YuApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(GATEWAY_HOST + "/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(GATEWAY_HOST + "/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        HashMap<String, String> header = new HashMap<>();
        header.put("accessKey", accessKey);
        //secretKey一定不能直接发给后端
//        header.put("secretKey", secretKey);
        header.put("nonce", RandomUtil.randomNumbers(4));
        header.put("body", body);
        header.put("timestamp", String.valueOf(System.currentTimeMillis()));
        header.put("sign", genSign(body, secretKey));
        return header;
    }


    public String getUsernameByPost(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/name/user/")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }
}
